package com.common.http;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpUtils {

	private static final String UTF_8 = "UTF-8";

	public static String sendPost(String data, String url, HashMap<String, String> headerMap) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);// 创建httpPost
		for (Map.Entry<String, String> entry : headerMap.entrySet()) {
			httpPost.setHeader(entry.getKey(), entry.getValue());
		}
		String charSet = "UTF-8";
		StringEntity entity = new StringEntity(data, charSet);
		httpPost.setEntity(entity);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(100000)
				.setConnectionRequestTimeout(100000).setSocketTimeout(100000).build();// 设置请求和传输超时时间
		httpPost.setConfig(requestConfig);
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httpPost);
			StatusLine status = response.getStatusLine();
			int state = status.getStatusCode();
			if (state == HttpStatus.SC_OK || state == HttpStatus.SC_ACCEPTED) {
				HttpEntity responseEntity = response.getEntity();
				String jsonString = EntityUtils.toString(responseEntity, "UTF-8");
				return jsonString;
			} else {
				return "error";
			}
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
			return "SocketTimeout";
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpPost.releaseConnection();
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * GET请求
	 *
	 * @param url    请求地址
	 * @param params 请求参数
	 * @return 返回结果
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @Date:2018年02月03日
	 */
	public static String get(String url, Map<String, Object> params, HashMap<String, String> headerMap)
			throws ClientProtocolException, IOException {
		URIBuilder ub = new URIBuilder();
		ub.setPath(url);
		if (params != null && params.size() > 0) {
			List<NameValuePair> pairs = covertParams2Nvps(params);
			ub.setParameters(pairs);
		}
		HttpGet httpGet = null;
		try {
			httpGet = new HttpGet(ub.build());
			for (Map.Entry<String, String> entry : headerMap.entrySet()) {
				httpGet.setHeader(entry.getKey(), entry.getValue());
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return handlerRequest(httpGet);
	}

	/**
	 * 封装请求参数
	 *
	 * @param params 请求参数
	 * @return 返回结果
	 * @Date:2018年02月03日
	 */
	private static List<NameValuePair> covertParams2Nvps(Map<String, Object> params) {
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		for (Map.Entry<String, Object> param : params.entrySet()) {
			pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
		}
		return pairs;
	}

	/**
	 * 处理Http请求
	 *
	 * @param httpRequestBase
	 * @return 返回结果
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @Date:2018年02月03日
	 */
	private static String handlerRequest(HttpRequestBase httpRequestBase) throws ClientProtocolException, IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = httpClient.execute(httpRequestBase);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			String result = EntityUtils.toString(entity, UTF_8);
			response.close();
			return result;
		}
		return null;
	}
}
